//
//  PayVC.m
//  Arts1
//
//  Created by Mac Jc on 15/10/12.
//  Copyright © 2015年 Arts1. All rights reserved.
//

#import "PayVC.h"
#import "AllHeader.h"
#import "CourseDetailHeadView.h"
#import "PayNavigationView.h"
//  支付宝支付
#import "Order.h"
#import <AlipaySDK/AlipaySDK.h>
#import "DataSigner.h"


//#define SucPayURL @""

@interface PayVC ()<UITableViewDataSource,UITableViewDelegate>
// 自定义navigation视图
@property (nonatomic, strong) PayNavigationView *navigationview;

//  价格视图
@property (nonatomic, strong) UIView *priceView;
@property (nonatomic, strong) UILabel *titleLabel;
@property (nonatomic, strong) UILabel *priceLabel;
@property (nonatomic, strong) UIButton *selectButton;


//  选择支付方式
@property (nonatomic, strong) UITableView *tableView;


@end

@implementation PayVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = kBackgroundColor;
    self.navigationController.navigationBar.hidden = YES;
    
    [self createNavigationBar];
    [self creativePriceView];
    [self creativeThirdPayView];
}

// 自定义navigationbar
- (void)createNavigationBar{
    _navigationview = [[PayNavigationView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    _navigationview.backgroundColor = [UIColor whiteColor];
    _navigationview.mainTitleLabel.text = @"在线支付";
    [self.view addSubview:_navigationview];
    //  给返回按钮添加点击事件
    [_navigationview.backButton addTarget:self action:@selector(backBefore) forControlEvents:(UIControlEventTouchUpInside)];
}


// 返回上一层
- (void)backBefore{
    [self.navigationController popViewControllerAnimated:YES];
    //    self.tabBarController.tabBar.hidden = NO;
//    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)creativeThirdPayView{
    
    UIView *thirdPayView = [[UIView alloc] initWithFrame:CGRectMake(0, _priceView.bottom + 40, SCREEN_WIDTH, 100)];
    thirdPayView.backgroundColor = [UIColor whiteColor];
    
    UILabel *describePayLabel = [[UILabel alloc] initWithFrame:CGRectMake( 15, 10, 200, 20)];
    describePayLabel.text = @"使用第三方平台支付";
    describePayLabel.font = [UIFont systemFontOfSize:14];
    describePayLabel.textColor = kCustomColor(50, 50, 70, 1);
    [thirdPayView addSubview:describePayLabel];
    
    UIView *lineView1 = [[UIView alloc] initWithFrame:CGRectMake(0, describePayLabel.bottom + 10, SCREEN_WIDTH, 0.5)];
    lineView1.backgroundColor = kCustomColor(150, 150,150, 0.5);
    [thirdPayView addSubview:lineView1];
    
    UIImageView *zhifubaoImageView = [[UIImageView alloc] initWithFrame:CGRectMake(20, lineView1.bottom + 10, 40, 40)];
    zhifubaoImageView.image = [UIImage imageNamed:@"zhifubao"];
    zhifubaoImageView.layer.cornerRadius = 7;
    zhifubaoImageView.layer.masksToBounds = YES;
    [thirdPayView addSubview:zhifubaoImageView];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(zhifubaoImageView.right + 10, zhifubaoImageView.top - 2, 100, 20)];
    titleLabel.text = @"支付宝";
    titleLabel.textColor = kCustomColor(50, 50, 70, 1);
    titleLabel.font = [UIFont systemFontOfSize:14];
    [thirdPayView addSubview:titleLabel];
    
    UILabel *subtitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(zhifubaoImageView.right + 10, zhifubaoImageView.bottom - 13, 220, 13)];
    subtitleLabel.text = @"推荐已安装支付宝客户端的用户使用";
    subtitleLabel.textColor = kCustomColor(50, 50, 70, 1);
    subtitleLabel.font = [UIFont systemFontOfSize:12];
    [thirdPayView addSubview:subtitleLabel];
    
    //    UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 25, SCREEN_WIDTH, 0.5)];
    //    lineView2.backgroundColor = kCustomColor(150, 150,150, 0.5);
    //    [thirdPayView addSubview:lineView1];
    
    _selectButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    _selectButton.frame = CGRectMake(SCREEN_WIDTH - 42,lineView1.bottom + zhifubaoImageView.size.height / 2 - 1, 22, 22);
    [_selectButton setImage:[UIImage imageNamed:@"selectButtonSelected"] forState:(UIControlStateNormal)];
    //    [_selectButton setImage:[UIImage imageNamed:@"selectButtonSelected"] forState:(UIControlStateReserved)];
    [thirdPayView addSubview:_selectButton];
    
    UIButton *payButton = [UIButton buttonWithType:(UIButtonTypeRoundedRect)];
    payButton.frame = CGRectMake(15, thirdPayView.bottom + 80, SCREEN_WIDTH - 30, 40);
    payButton.backgroundColor = kCustomColor(50, 50, 70, 1);
    payButton.layer.cornerRadius = 5;
    payButton.layer.masksToBounds = YES;
    [payButton setTitle:@"确认支付" forState:(UIControlStateNormal)];
    [payButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [payButton addTarget:self action:@selector(tapToPay:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:payButton];
    
    [self.view addSubview:thirdPayView];
}
/**
 *   确认支付，跳转到响应的付款方式登陆页面
 */
- (void)tapToPay:(UIButton *)button{
    NSLog(@"确认支付,转到支付宝");
    [self alipay];
    
}
/**
 *  支付宝 == 支付调用方法
 */
- (void)alipay{
    //1  商户 ID
    NSString *partner = @"2088021725042722";
    //2   商户收款帐号
    NSString *seller = @"arts1@arts1.cn";
    //3   商户私钥
//    NSString*privateKey = @"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALQiWWiRjCq5I3v4cEK9GSPnmI6UJUgFEWU7XKV7DULQqLIq7iQlg1OIECT6htXNK8JsQ6DvTu/Fg39VtxD6ENMDQsr8mmDhU/snf1EgmmZtDmrJWReuKnz/udDPqXO5uSyc6yms7X7rmgH99vx0sT23T4mh347b5cRkBFlBj0XdAgMBAAECgYEAo1IxdlngmCvcPF54ikohLSiibUNsueu+ZeZ4jaEP2PCOw1uhJyzL8USAPsbW0aqAbnrypkvTahnOq/jvTnksHl+GtegK70hOzxw6sXvYUbtYpfCZ5rtUHy7h8XgaDOwtfvnoHdjLDuNjWMlfBdQwMCxtizeIWvWNUf0BJf/aGxECQQDmkuiYChB51yRM5ZgD3BLltMOSEDuYiW2qhVl9fYRJ8Ct6IPyzK9IofTbSDZ3LCQjf9i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74NYGZWOgVx/RIpSk5RMeyGvlh0r0FuZIwVzQJTzI3IzMXN8Vb7LFwyfEUewaFkQJANVHwZBpRvHq6OeYJ9qVddoxCIMKHcICXFIOkuMM5CGjKEYD4zhSXh0yxt/pJJMkgOGMIsaKcfAznNBgVM/3KwA==";
    
    
    //123 申请好后支付宝SDK 会提供
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    

    
    NSLog(@" 支付创建订单  返回数据 ： %@ ",_oderDictionary);
    
    //支付宝 SDK 订单对象
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = _oderDictionary[@"orderNum"];  //订单ID（由商家自行制定）
    order.productName = _oderDictionary[@"ordertitle"]; //商品标题
//    order.productDescription = @"这只是一个测试"; //商品描述
    order.amount = _oderDictionary[@"orderMoney"]; //商品价格
//    [NSString stringWithFormat:@"%@/Notify/Alipay/", URLHEADER];
//    order.notifyURL = @"http://www.arts1.cn/alipay/notify_url.php"; //回调URL(旧)
    order.notifyURL = @"http://www.arts1.cn/pay/alipay-notify.html"; //回调URL（新）
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";

    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串，该方法支付宝已经封好，即生成订单描述
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    
    //下面调用支付宝 sdk
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    //调用签名
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            
            //支付结果
            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
                //9000为支付成功
                NSLog(@" 支付宝支付成功 ");
                NSLog(@"reslut = %@",resultDic);
//                [self requestDataForPayForService];
            }
            
        }];
        [self backBefore];
        if (_successpaylock) {
            _successpaylock();
        }
        
    }
    


    
}



- (void)selectTap:(UIButton *)button{
    [_selectButton setImage:[UIImage imageNamed:@"selectButtonSelected"] forState:(UIControlStateNormal)];
}


- (void)creativePriceView{
    
    _priceView = [[UIView alloc] initWithFrame:CGRectMake(0, 104, SCREEN_WIDTH, 40)];
    _priceView.backgroundColor = [UIColor whiteColor];
    
    _titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(_priceView.left + 15, 10, 100, 20)];
    _titleLabel.text = @"支付总额";
    _titleLabel.textColor = kCustomColor(50, 50, 70, 1);
    _titleLabel.font = [UIFont systemFontOfSize:14];
    [_priceView addSubview:_titleLabel];
    
    _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 70, _titleLabel.top, 100, 20)];
    [_titleLabel setTextAlignment:(NSTextAlignmentLeft)];
    _priceLabel.font = [UIFont boldSystemFontOfSize:14];
    _priceLabel.text = [NSString stringWithFormat:@"￥%@",_oderDictionary[@"orderMoney"]];
    _priceLabel.textColor = kCustomColor(50, 50, 70, 1);
    [_priceView addSubview:_priceLabel];
    
    [self.view addSubview:_priceView];
    
}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - 数据源方法
#pragma mark 返回分组数
//-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//
//    return 2;
//}

#pragma mark 返回每组行数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //    if (section == 0) {
    //        return 3;
    //    }else{
    //        return 1;
    //    }
    return 4;
}

#pragma mark返回每行的单元格
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //    if (indexPath.section == 0) {
    //        if (indexPath.row == 1) {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"payWithThird"];
    cell.textLabel.text = @"使用第三方平台支付";
    return cell;
    //        }else {
    //            ThirdPayTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"thirdPayCell"];
    //            cell.iconImageView.image = [UIImage imageNamed:@"zhifubao"];
    //            cell.titleLabel.text = @"支付宝";
    //            cell.subtitleLabel.text = @"推荐支付宝用户使用";
    //            return cell;}
    //    }else{
    //        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"conferPay"];
    //        cell.textLabel.text = @"确认支付";
    //        return cell;
    //    }
}



//#pragma mark 返回每组头标题名称
//-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//    NSLog(@"生成组（组%i）名称",section);
//    KCContactGroup *group=_contacts[section];
//    return group.name;
//}

//#pragma mark 返回每组尾部说明
//-(NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section{
//    NSLog(@"生成尾部（组%i）详情",section);
//    KCContactGroup *group=_contacts[section];
//    return group.detail;
//}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
